package com.kkshop.gwt.login;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.XMLParser;
import com.kkshop.gwt.base.Controller;

public class LoginController implements Controller {

    private static final String CONTAINER_ID = "loginContainer";
    private static final String FAILURE_LOGIN_STATUS_CODE = "ERROR";
    private static final String SUCCESS_LOGIN_STATUS_CODE = "SUCCESS";
    
    private LoginView view;

    public void initialize() {
        view = new LoginView();
        view.getForm().addFormHandler(new LoginFormHandler());
        view.getSubmitButton().addClickListener(new OnSubmitHandler());
        RootPanel.get(CONTAINER_ID).add(view.getWidget());
    }
    
    private String getElementText(Document document, String elementName) {
        return document.getDocumentElement().getElementsByTagName(elementName).item(0).getFirstChild().getNodeValue();
    }
    
    private class LoginFormHandler implements  FormHandler {
        public void onSubmit(FormSubmitEvent event) {
            view.getSubmitButton().setEnabled(false);
        }

        public void onSubmitComplete(FormSubmitCompleteEvent event) {
            Document doc = XMLParser.parse(event.getResults().trim());
            String code = getElementText(doc, "code");
            if(SUCCESS_LOGIN_STATUS_CODE.equalsIgnoreCase(code)) {
                Window.open("/secure/main.action", "_self", null);
            } else if(FAILURE_LOGIN_STATUS_CODE.equalsIgnoreCase(code)) {
                view.getMessageAreaHtml().setHTML("User name or password is incorrect!");
            } else {
                view.getMessageAreaHtml().setHTML("Sorry! Try to login later...");
            }
            view.getSubmitButton().setEnabled(true);
        }
    }
    
    private class OnSubmitHandler implements ClickListener {
        public void onClick(Widget widget) {
            view.getForm().submit();
        }
    }

    public String getContainerId() {
        return CONTAINER_ID;
    }
}
